<template>
  <BoTable
    :columns="columns"
    :request="getDeviceVersionList"
    ref="tableRef"
    :row-selection="rowSelection"
    row-key="versionId"
  >
    <template #toolbars>
      <Space>
        <Button type="primary" @click="onAdd"> 新增推送版本 </Button>
        <Button @click="onDelete(null)" :disabled="!selectKeys.length">
          删除
        </Button>
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items" ref="addFormRef"> </FormModal>
  <!-- 推送弹窗 -->
  <FormModal2 :columns="itemsPush">
    <template #pushTable>
      <FormItemRest>
        <Push v-model:value="selectRows"></Push>
      </FormItemRest>
    </template>
  </FormModal2>
  <!-- 推送记录弹窗 -->
  <FormModal3 :columns="itemsPushRecord">
    <template #pushTable>
      <PushRecord :versionId="versionId"></PushRecord>
    </template>
  </FormModal3>

  <!--推送  -->
  <SseModal />
</template>
<route lang="json">
{
  "name": "upgrade",
  "meta": {
    "title": "固件升级"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { BoFormProps, BoTable, BoTableProps, BoUploadFile } from '@boeyo/ui';
import { Button, FormItemRest, Modal, Space, message } from 'ant-design-vue';
import { useSseModal } from '@/hooks/useSseModal';
import {
  AddDeviceVersion,
  addVersionPush,
  deleteDeviceVersion,
  getDeviceVersionList,
  uploadFile,
} from './api';
import PushRecord from './components/push-record/index.vue';
import Push from './components/push/index.vue';

// 推送页面选中行
const selectRows = ref<any[]>([]);

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

const dictArr = ['file_upgrade_type', 'push_record'];
const { fileUpgradeTypeEnum, fileUpgradeTypeOptions } = useDicts(dictArr);

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '文件名',
    dataIndex: 'filename',
  },
  {
    title: '文件版本',
    dataIndex: 'version',
    hideInSearch: true,
  },
  {
    title: '文件类型',
    valueType: 'select',
    dataIndex: 'fileType',
    valueEnum: fileUpgradeTypeEnum.value,
  },
  // {
  //   title: '状态',
  //   dataIndex: 'status',
  //   valueType: 'status',
  //   valueEnum: useStatusEnum.value,
  // },
  {
    title: '版本说明',
    dataIndex: 'versionDesc',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '推送',
        onClick(record) {
          onPush(record);
        },
      },
      {
        text: '推送记录',
        onClick(record) {
          onPushRecord(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '文件名',
    dataIndex: 'filename',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入文件名',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入文件名',
    },
  },
  {
    title: '文件类型',
    dataIndex: 'fileType',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择文件类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择文件类型',
      options: fileUpgradeTypeOptions.value as any,
    },
  },
  {
    title: '文件版本',
    dataIndex: 'version',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入文件版本',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入文件版本',
    },
  },
  {
    title: '版本说明',
    dataIndex: 'versionDesc',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入版本说明',
    },
  },
  // {
  //   title: '状态',
  //   dataIndex: 'status',
  //   valueType: 'radio',
  //   fieldProps: {
  //     placeholder: '请选择状态',
  //     options: useStatusOptions.value,
  //   },
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请选择状态',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  // },
  {
    title: '推送文件',
    dataIndex: 'fileUrl',
    valueType: 'input',
    render: (state) => {
      return (
        <BoUploadFile
          title='点击上传'
          uploadApi={uploadFile}
          onSuccess={(res) => onUploadSuccess(res.filePath, state)}
        ></BoUploadFile>
      );
    },
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请点击上传',
          trigger: 'blur',
        },
      ],
    },
  },
]);
const itemsPush = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'pushTitle',
    valueType: 'input',
    render(state) {
      return <span class='module-title mb-0'>推送信息</span>;
    },
    colProps: {
      span: 24,
    },
  },
  {
    title: '文件名',
    dataIndex: 'filename',
    valueType: 'input',
    render(state) {
      return <div>{state.filename}</div>;
    },
  },
  {
    title: '文件类型',
    dataIndex: 'fileType',
    valueType: 'select',
    render(state) {
      return (
        <div class='ml-2'>{fileUpgradeTypeEnum.value[state.fileType].text}</div>
      );
    },
  },
  {
    title: '文件版本',
    dataIndex: 'version',
    valueType: 'input',
    render(state) {
      return <div class='ml-2'>{state.version}</div>;
    },
  },
  {
    title: '版本说明',
    dataIndex: 'versionDesc',
    valueType: 'input',
    render(state) {
      return <div class='ml-2'>{state.versionDesc}</div>;
    },
  },
  {
    title: '推送文件',
    dataIndex: 'fileUrl',
    valueType: 'input',
    render(state) {
      return <div class='ml-2'>{state.fileUrl}</div>;
    },
    colProps: {
      span: 16,
    },
    formItemProps: {
      labelCol: { span: 2 },
      wrapperCol: { span: 18 },
    },
  },
  {
    title: '',
    dataIndex: 'pushTitle',
    valueType: 'input',
    render(state) {
      return <div class='module-title mb-0'>选择设备</div>;
    },
    colProps: {
      span: 24,
    },
  },
  {
    title: '',
    dataIndex: 'pushTable',
    valueType: 'input',
    formItemProps: {
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
    },
    colProps: {
      span: 24,
    },
  },
]);
const itemsPushRecord = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'pushTable',
    valueType: 'input',
    formItemProps: {
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
    },
    colProps: {
      span: 24,
    },
  },
]);

// 新增推送版本
const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 2,
});
// 推送弹窗
const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  column: 3,
  confirmText: '推送',
});
// 推送记录弹窗
const { FormModal: FormModal3, open: open3 } = useFormModal({
  size: 'middle',
  column: 2,
});

// 查看推送记录
const versionId = ref(0);
const onPushRecord = (record: any) => {
  versionId.value = record.versionId;
  open3({
    title: '推送记录',
    request: async (params: any) => {
      tableRef.value.refresh();
    },
    defaultValue: {
      ...record,
    },
  });
};

// 推送
//实现自定义异步函数
function createPromise() {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
const { SseModal, open: openSse } = useSseModal();
const onPush = (record: any) => {
  open2({
    title: '推送',
    showMessage: false,
    request: async () => {
      const { resolve, promise, reject } = createPromise();
      const deviceIds = selectRows.value?.map((item: any) => {
        return item.deviceId;
      });
      if (!selectRows.value?.length) {
        reject();
        message.info('请选择设备');
        throw new Error('请选择设备');
      }
      const res = await addVersionPush({ versionId: record.versionId });
      // SSE方式保存数据
      openSse({
        title: '推送',
        url: '/api/versionPushLog/add',
        data: {
          deviceId: deviceIds,
          versionId: record.versionId,
          versionPushTotalId: res.data,
        },
        method: 'post',
        onClose() {
          resolve(1);
        },
      });
      await promise;
      selectRows.value = [];
      tableRef.value.refresh();
    },
    defaultValue: {
      ...record,
    },
  });
};

const addFormRef = ref();
const onAdd = () => {
  open({
    title: '新增推送版本',
    request: async (params: any) => {
      await AddDeviceVersion(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      status: '0',
      fileUrl: '',
    },
  });
};

const onDelete = (record: any) => {
  const ids = record ? record.versionId : selectKeys.value.join();
  if (!ids) return message.info('请选择推送版本');
  Modal.confirm({
    title: '删除',
    content: '确定删除当前选中项数据吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await deleteDeviceVersion(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};

// 上传推送文件成功回调
// 父组件自己调用时，手动传入参数
const onUploadSuccess = (fileName, state) => {
  state.fileUrl = fileName;
};
</script>

<style lang="scss" scoped></style>
